package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.app.BaseApp;
import com.atguigu.edu.bean.CartAddUuBean;
import com.atguigu.edu.common.Constant;
import com.atguigu.edu.util.AtguiguUtil;
import com.atguigu.edu.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.ParseException;
import java.time.Duration;

public class Dws_08_TradeCartAddUuWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_08_TradeCartAddUuWindow().init(
                4008,
                2,
                "Dws_08_TradeCartAddUuWindow",
                Constant.TOPIC_DWD_TRADE_CART_ADD
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment ev, DataStreamSource<String> stream) {
        stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
//                                .withTimestampAssigner((obj, ts) -> {
//                                    try {
//                                        return AtguiguUtil.dateToTs(String.valueOf(obj.getLong("create_time")));
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                        return System.currentTimeMillis();
//                                    }
//                                })
                                .withTimestampAssigner((obj, ts) -> obj.getLong("create_time"))
                                .withIdleness(Duration.ofSeconds(60))

                )
                .keyBy(obj -> obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {

                    private ValueState<String> lastCartAddDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastCartAddDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastCartAddDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<CartAddUuBean> out) throws Exception {
                        long ts = obj.getLong("create_time");
                        String today = AtguiguUtil.tsToDate(ts);

                        Long cartAddUuCt = 0L;

                        if (!today.equals(lastCartAddDateState.value())) {
                            // 今天第一次加购
                            cartAddUuCt = 1L;
                            lastCartAddDateState.update(today);
                        }

                        if (cartAddUuCt == 1) {
                            out.collect(new CartAddUuBean("", "", cartAddUuCt, ts));
                        }

                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<CartAddUuBean>() {
                            @Override
                            public CartAddUuBean reduce(CartAddUuBean value1,
                                                        CartAddUuBean value2) throws Exception {
                                value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());

                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<CartAddUuBean> elements,
                                                Collector<CartAddUuBean> out) throws Exception {
                                CartAddUuBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                )
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_cart_add_uu_window", CartAddUuBean.class));
    }
}
